import cv2
from random import randint
import numpy as np

char2idx_dict = {"京": 0, "沪": 1, "津": 2, "渝": 3, "冀": 4, "晋": 5, "蒙": 6, "辽": 7, "吉": 8, "黑": 9, "苏": 10,
                 "浙": 11, "皖": 12, "闽": 13, "赣": 14, "鲁": 15, "豫": 16, "鄂": 17, "湘": 18, "粤": 19, "桂": 20,
                 "琼": 21, "川": 22, "贵": 23, "云": 24, "藏": 25, "陕": 26, "甘": 27, "青": 28, "宁": 29, "新": 30,
                 "0": 31, "1": 32, "2": 33, "3": 34, "4": 35, "5": 36, "6": 37, "7": 38, "8": 39, "9": 40,
                 "A": 41, "B": 42, "C": 43, "D": 44, "E": 45, "F": 46, "G": 47, "H": 48, "J": 49, "K": 50,
                 "L": 51, "M": 52, "N": 53, "P": 54, "Q": 55, "R": 56, "S": 57, "T": 58, "U": 59, "V": 60,
                 "W": 61, "X": 62, "Y": 63, "Z": 64}


# 生成一个数值与车牌字符的对应字典
def idx2char():
    return {f"{k}": v for k, v in enumerate(char2idx_dict.keys())}


idx2char_dict = idx2char()


# 随机生成车牌信息
def get_panel_info():
    # ---- 生成车牌的随机下标----
    chrs = []
    city_num = randint(0, 30)
    letter_num = randint(41, 64)
    chrs.append(city_num)
    chrs.append(letter_num)
    chrs.append(randint(31, 64))
    chrs.append(randint(31, 64))
    chrs.append(randint(31, 64))
    chrs.append(randint(31, 64))
    chrs.append(randint(31, 64))
    # ---- 对应车牌下标生成对应的字符串----
    panel_str = ""
    for n in chrs:
        panel_str += idx2char_dict[f"{n}"]
    return panel_str


# 生成车牌图片并且保存
def product_panel(panel_str):
    # 车牌
    panel_back = cv2.imread("./img/panels/back/blue_140.PNG")
    panel_back = cv2.resize(panel_back, (440, 140))
    s = 0
    for i, chr in enumerate(panel_str):
        panel_element = cv2.imdecode(np.fromfile(f"./img/panels/font/140_{chr}.jpg", dtype=np.uint8), 1)
        # 获取文字的宽高比例
        h, w, _ = panel_element.shape
        scale = w / h
        # 改变车牌首写城市字的大小
        panel_element = cv2.resize(panel_element, (40, 80))
        # 将城市字设置为黑底白色
        panel_element = 255 - panel_element
        # 重新获取字体大小的值
        w, h = 40, 80
        # 根据字体不同的位置判断s的距离
        if i == 0:
            s += 20
        elif i == 2:
            s += 40
        else:
            s += 15
        # 从车牌的区域抠出一块区域给城市字体
        part1 = panel_back[30:30 + h, (w * i + s):(w * (i + 1) + s)]
        # 将上述的区域与城市字体进行“图像融合”
        result = cv2.bitwise_or(part1, panel_element)
        # 将融合区域再次赋值给整个车牌
        panel_back[30:30 + h, (w * i + s):(w * (i + 1) + s)] = result
    return panel_back


# image = product_panel(get_panel_info())
# cv2.imshow("panel", image)
# cv2.waitKey(0)

# 连续保存10张车牌
for i in range(1):
    name = get_panel_info()
    image = product_panel(name)
    # 保存图片
    cv2.imwrite(f"./img/panels/product/{name}.jpg", image)
